package rapier.sso.server.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

public class BeanUtils extends org.springframework.beans.BeanUtils {
	public static void copyProperties2Map(Object source, Map<String, Object> target) {
		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		for (String targetKey : target.keySet()) {
			PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetKey);
			if (sourcePd != null) {
				Method readMethod = sourcePd.getReadMethod();
				if (readMethod != null) {
					try {
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						target.put(targetKey, value);
					} catch (Throwable ex) {
						throw new FatalBeanException(
								"Could not copy property '" + targetKey + "' from source to target", ex);
					}
				}
			}
		}
	}
}
